package org.popupcommunication.service.impl;

import java.util.List;

import org.popupcommunication.dao.GroupDAO;
import org.popupcommunication.dao.UserDAO;
import org.popupcommunication.model.Group;
import org.popupcommunication.model.User;
import org.popupcommunication.service.GroupManager;
import org.popupcommunication.utils.Slug;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.Errors;

@Transactional
public class GroupManagerBean implements GroupManager{
	@Autowired
	private UserDAO userRepository;
	
	private GroupDAO groupRepository;

	public GroupDAO getGroupRepository() {
		return groupRepository;
	}

	public void setGroupRepository(GroupDAO groupRepository) {
		this.groupRepository = groupRepository;
	}

	@Override
	public boolean registerGroup(Group g, String name, Errors errors) {
        if (groupRepository.findByName(name) != null)    {
        	errors.rejectValue("name", "group.exist", new String[]{name}, null);
        }
        boolean valid = !errors.hasErrors();
        if (valid){
        	g.setSlug(new Slug().makeSlug(g.getName()));
        	groupRepository.add(g); 
        	//ajouter le groupe aux administrateurs
        	List<User> admins = userRepository.getAdmins();
        	for(User a: admins){
        		g = groupRepository.merge(g);
        		a.addGroup(g);
        		g.addUser(a);
        	}
        }
        return valid;
	}

	@Override
	public List<Group> getAllGroups() {
		List<Group> lg= groupRepository.getAllGroupDao();	
		return lg;
	}

	@Override
	public Group findByName(String n) {
		return groupRepository.findByName(n);
	}

	@Override
	public Group findById(Integer i) {
		return groupRepository.findById(i);
	}

	@Override
	public Group findBySlug(String s) {
		return groupRepository.findBySlug(s);
	}

}
